from rest_framework import serializers

from apps.goods.models import SKU


class CartSerializers(serializers.Serializer):
    sku_id = serializers.IntegerField(min_value=1, label="商品id")
    count = serializers.IntegerField(min_value=1, max_value=200, label="商品数量")
    selected = serializers.BooleanField(default=True, required=False)  # 是否勾选

    #多字段校验
    def validate(self, attrs):
        # 获取数据
        sku_id = attrs.get("sku_id")
        count = attrs.get("count")

        # 判断商品是否存在
        try:
            sku = SKU.objects.get(id=sku_id)
        except Exception as e:
            raise serializers.ValidationError("商品不存在")

        # 判断加入购物车数量是否大于库存量
        if sku.stock < count:
            raise serializers.ValidationError("库存不足")

        return  attrs


